package com.dy.lock.screen.api.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.dy.lock.screen.api.constants.Constant;
import com.dy.lock.screen.api.scoket.Head;
import com.dy.lock.screen.api.scoket.SocketDTO;
import com.dy.lock.screen.api.server.HttpServerStartMain;
import com.dy.lock.screen.api.utils.CommonUtil;
import com.dy.lock.screen.api.utils.DateUtil;
import com.dy.lock.screen.api.utils.IpUtil;
import com.dy.lock.screen.api.utils.MD5Util;
import com.dy.lock.screen.api.utils.ServletUtil;
import com.dy.lock.screen.api.vo.ResultVo;
import com.dy.lock.screen.api.vo.UserResultVo;
import com.google.gson.Gson;

/**
 * 上传图片
 * 
 * @description
 * @author
 * @date
 */
public class UploadImageServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(UploadImageServlet.class);
	private static Gson gson = CommonUtil.gson();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);
		try {
			String loadpath = HttpServerStartMain.getValue("photo.location")
					+ Constant.UPLOAD_IMAGE_PATH; // 上传文件存放目录
			String temp = loadpath; // 临时目录
			File file = new File(loadpath);
			if (!file.exists()) {
				file.mkdirs();
			}

			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024 * 1024);
			factory.setRepository(new File(temp)); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 开始读取上传信息
			List<FileItem> fileItems = upload.parseRequest(req);
			StringBuffer sBuffer = new StringBuffer();

			if (fileItems != null && fileItems.size() > 0) {
				FileItem item = fileItems.get(0);// 忽略其他不是文件域的所有表单信息
				if (!item.isFormField()) {
					String name = item.getName();// 获取上传文件名,包括路径
					name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
					long size = item.getSize();
					if ((name == null || name.equals("")) && size == 0) {
						ServletUtil.writeErrorStr(resp);
						return;
					}
					name = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "_"
							+ CommonUtil.createRandomNumber() + ".jpg";
					File fNew = new File(loadpath, name);
					item.write(fNew);
					sBuffer.append(Constant.UPLOAD_IMAGE_PATH + name);
				}
			}
			// Iterator<FileItem> iter = fileItems.iterator(); // 依次处理每个上传的文件
			// while (iter.hasNext()) {
			// FileItem item = iter.next();// 忽略其他不是文件域的所有表单信息
			// if (!item.isFormField()) {
			// String name = item.getName();// 获取上传文件名,包括路径
			// name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
			// long size = item.getSize();
			// if ((name == null || name.equals("")) && size == 0)
			// continue;
			// name = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "_"
			// + index + "_" + CommonUtil.createRandomNumber()
			// + ".jpg";
			// index++;
			// File fNew = new File(loadpath, name);
			// item.write(fNew);
			// sBuffer.append(Constant.UPLOAD_IMAGE_PATH + name);
			// }
			// else// 取出不是文件域的所有表单信息
			// {
			// String fieldvalue = item.getString();
			// 如果包含中文应写为：(转为UTF-8编码)
			// String fieldvalue = new
			// String(item.getString().getBytes(),"UTF-8");
			// }
			// }
			ResultVo ri = new ResultVo();
			ri.setCode(Constant.SUCCESS);
			ri.setStatus(Constant.TRUE);
			ri.setData(sBuffer.toString());
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));

		} catch (Exception e) {
			log.error("解析图片流异常", e);
			ServletUtil.writeErrorStr(resp);
		}
	}

	/**
	 * 向service服务发送请求
	 * 
	 * @param t
	 * @param req
	 * @return
	 */
	@SuppressWarnings("unused")
	private SocketDTO sendMessage(String vo, HttpServletRequest req) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.UPLOAD_IMAGE);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("api");
		return super.send(head, vo);
	}

	/**
	 * 数据校验合法性
	 * 
	 * @param userId
	 * @param sign
	 * @param resp
	 * @param req
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private boolean validateData(String sign, String image,
			HttpServletResponse resp, HttpServletRequest req)
			throws IOException {
		UserResultVo ri = new UserResultVo();
		boolean result = false;
		if (StringUtils.isEmpty(image)) {
			log.info("图片内容为空!!!");
			ri.setCode(Constant.IMAGE_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
		} else if (StringUtils.isEmpty(sign)) {
			log.info("签名字符串为空!!!");
			ri.setCode(Constant.SIGN_IS_NULL);
			ri.setStatus(Constant.FALSE);
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
			return false;
		} else {
			String key = HttpServerStartMain.getValue("dou.yang.key");
			StringBuilder builder = new StringBuilder();
			builder.append("image");
			builder.append(image);
			builder.append("key");
			builder.append(key);

			String data = builder.toString();

			boolean checked = MD5Util.checkMD5Signature(data, sign);
			if (checked) {
				result = true;
			} else {
				log.info("数字签名失败！！！");
				ri.setCode(Constant.CHECK_SIGN_FAIL);
				ri.setStatus(Constant.FALSE);
				ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
				return false;
			}
		}

		return result;
	}
}
